<?php
class StringTool
{
	/**
	 * 
	 * 自动转换字符集 支持数组转换
	 */
	public static function auto_charset($contents, $from, $to)
	{
	    $from = strtoupper($from)=='UTF8'? 'utf-8':$from;
	    $to = strtoupper($to)=='UTF8'? 'utf-8':$to;
	    if(strtoupper($from) === strtoupper($to) || empty($contents) || (is_scalar($contents) && !is_string($contents)) )
	    {
	        //如果编码相同或者非字符串标量则不转换
	        return $contents;
	    }
	    if(is_string($contents)) 
	    {
	        if(function_exists('mb_convert_encoding'))
	        {
	            return mb_convert_encoding ($contents, $to, $from);
	        }
	        elseif(function_exists('iconv'))
	        {
	            return iconv($from,$to,$contents);
	        }
	        else
	        {
	            return $contents;
	        }
	    }
	    elseif(is_array($contents))
	    {
	        foreach ( $contents as $key => $val )
	        {
	            $_key = auto_charset($key,$from,$to);
	            $contents[$_key] = auto_charset($val,$from,$to);
	            if($key != $_key )
	                unset($contents[$key]);
	        }
	        return $contents;
	    }
	    else
	    {
	        return $contents;
	    }
	}
	
	
	/**
	 * 
	 * 截取字符串
	 * @param string $str
	 * @param int $length
	 * @param int $start
	 * @param string $suffix
	 * @param string $charset
	 * @return string
	 */
	public static function mbsubstr($str, $length, $start = 0, $suffix = '......', $charset = "utf-8")
	{
	    //if(function_exists("mb_substr"))
	        //return mb_substr($str, $start, $length, $charset);
	    //elseif(function_exists('iconv_substr')) {
	        //return iconv_substr($str,$start,$length,$charset);
	    //}
	    $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
	    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
	    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
	    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
	    preg_match_all($re[$charset], $str, $match);
	    $slice = join("",array_slice($match[0], $start, $length));
	    if(count($match['0']) > $length) return $slice.$suffix;
	    return $slice;
	}
}
?>